package com.zyfdroid.mindnote2.utils;

import android.os.Handler;
import android.util.AndroidRuntimeException;

public class RunUtils {

    public static void runNoStrict(Runnable r){
        Thread t =new Thread(r);
        t.start();
        try {
            t.join();
        } catch (InterruptedException e) {
            throw new AndroidRuntimeException(e);
        }
    }


    public static class Promise<R>{

        private Handler handler;
        private PromiseResult<R> result;
        private PromiseCatch errHandler;

        private PromiseBody<R> body;

        public Promise(PromiseBody p){
            handler = new Handler();
            this.body = p;
            handler.post(this::doPromise);
        }

        private void doPromise(){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        R r = body.run();
                        if(result != null){

                           handler.post(()-> result.run(r));
                        }
                    }catch (Exception ex){
                        if(errHandler != null){
                             handler.post(()->errHandler.run(ex));
                        }
                    }
                }
            }).start();
        }


        public Promise then(PromiseResult<R> resultRunnable){
            this.result = resultRunnable;
            return this;
        }

        public Promise Catch(PromiseCatch catchClause){
            this.errHandler = catchClause;
            return this;
        }

        @FunctionalInterface
        public interface PromiseBody<T>{
            public T run() throws Exception;
        }
        @FunctionalInterface
        public interface PromiseResult<T>{
            public void run(T t);
        }
        @FunctionalInterface
        public interface PromiseCatch{
            public void run(Exception t);
        }
    }
}
